<?php
/*
Created On: 2 August, 2003.
Description: This is include file which is used to define the functions used in site.
*/

///////////////////////////////////////Function to Change Server Date to Indian Date and Time //////////

function indianDate()
{
$serverDate = date("Y-m-d H:i:s");
$date10Hour = mysql_query("select DATE_ADD('$serverDate', INTERVAL 10 HOUR ) ");
$After10Hour = mysql_result($date10Hour, 0, 0); 
$After10Hour30Minute = mysql_query("select DATE_ADD('$After10Hour', INTERVAL 30 MINUTE ) ");
$indDate = mysql_result($After10Hour30Minute, 0, 0); 
return $indDate;
}

/////////////////////////////////////// End of indianDate Function ////////////////////////////////////
function updatesecondsfromtime()
{
    $get_appt_sql ="select * from $finalize_appointment_table where 1=1 order by appt_id";
    $get_appt_query = mysql_query($get_appt_sql);
	while($get_appt_data = mysql_fetch_array($get_appt_query))
	{
	              $appt_id = $get_appt_data['appt_id'];
				  $apptstarttime = $get_appt_data['apptstarttime'];
				  $apptstarttimefrom_array = explode(" ",$apptstarttime); 
				  $apptstarttimefrom = $apptstarttimefrom_array[0];
				  $apptstarttypefrom = $apptstarttimefrom_array[1];
				  
				    if($apptstarttypefrom=="am")
					{
						 $timefrom_array = explode(":",$apptstarttimefrom);
						 $hourfrom = $timefrom_array[0];
						 $minutefrom = $timefrom_array[1];
						 $secondfrom = 0;
					}
					else
					{
						 $timefrom_array = explode(":",$apptstarttimefrom);
						 $hourfrom = 12 + $timefrom_array[0];
						 $minutefrom = $timefrom_array[1];
						 $secondfrom = 0;
					}
			
			        $start_seconds = mktime($hourfrom, $minutefrom, $secondfrom, 1, 1, 1970);
					
					$apptendtime = $get_appt_data['apptendtime'];
				    $apptendtimefrom_array = explode(" ",$apptendtime); 
				    $apptendtimefrom = $apptendtimefrom_array[0];
				    $apptendtypefrom = $apptendtimefrom_array[1];
				  
				    if($apptendtypefrom=="am")
					{
						 $timefrom_array = explode(":",$apptendtimefrom);
						 $hourfrom = $timefrom_array[0];
						 $minutefrom = $timefrom_array[1];
						 $secondfrom = 0;
					}
					else
					{
						 $timefrom_array = explode(":",$apptendtimefrom);
						 $hourfrom = 12 + $timefrom_array[0];
						 $minutefrom = $timefrom_array[1];
						 $secondfrom = 0;
					}
			
			        $end_seconds = mktime($hourfrom, $minutefrom, $secondfrom, 1, 1, 1970);
					
					$Update_Sql = "update $finalize_appointment_table set 
					apptstartseconds='$start_seconds',apptendseconds='$end_seconds' where appt_id='$appt_id'";
					
					mysql_query($Update_Sql);
	      
	}
	
}


function findendtime($start_time,$duration)
{
 
	$timefrom = substr($start_time, 0, -2);
	$typefrom = substr($start_time,-2);
	
	if($typefrom=="am")
	{
		 $timefrom_array = explode(":",$timefrom);
		 $hourfrom = $timefrom_array[0];
		 $minutefrom = $timefrom_array[1];
		 $secondfrom = 0;
	}
    else
	{
	     $timefrom_array = explode(":",$timefrom);
		 $hourfrom = 12 + $timefrom_array[0];
		 $minutefrom = $timefrom_array[1];
		 $secondfrom = 0;
	}
	
	
	$start_seconds = mktime($hourfrom, $minutefrom, $secondfrom, 1, 1, 1970);
	$value = explode(" ",$duration);
	$check_hours = strstr($duration,"hours");
	
	if($check_hours)
	{
	    $check_minutes = strstr($duration,"minutes");
		if($check_minutes)
		{
		   $hourvalue = $value[0];
		   $minutevalue = $value[2];
		   $duration_seconds =  $hourvalue*3600 +  $minutevalue*60;
		}
		else
		{
		   $hourvalue = $value[0];
		   $duration_seconds =  $hourvalue*3600;
		}
	    
	}
	else
	{ 
	      $minutevalue = $value[0];
		  $duration_seconds =  $minutevalue*60;
	}
    
	$end_seconds = $start_seconds + $duration_seconds;
				
	$end_time = date('h:i:s a', $end_seconds);
	
	return array($end_time,$start_seconds,$end_seconds);
}

function DatesBetween($startDate, $endDate){
    // get the number of days between the two given dates.
	
    $days = (strtotime($endDate) - strtotime($startDate)) / 86400 + 1;
    $startMonth = date("m", strtotime($startDate));
    $startDay = date("d", strtotime($startDate));
    $startYear = date("Y", strtotime($startDate));    
    $dates;//the array of dates to be passed back
    for($i=0; $i<$days; $i++){
        $dates[$i] = date("Y-m-d", mktime(0, 0, 0, $startMonth , ($startDay+$i), $startYear));
    }
    return $dates;    
}

function AddTime($date,$appoint_interval)
{
   /*echo "SELECT DATE_ADD('$date',INTERVAL $appoint_interval MINUTE)";
	echo "<br/>";*/
	$date_array = explode(" ",$date);
	$date_date = $date_array[0];  // 2007-11-05
	$date_time = $date_array[1];  // 08:00
	$date_type = $date_array[2];  // am
	$date = $date_date." ".$date_time.":00 ".$date_type;
	$dateaddmin = mysql_query("SELECT DATE_ADD('$date',INTERVAL $appoint_interval MINUTE)");
	$AfterNetDate = mysql_result($dateaddmin, 0, 0); 
	return $AfterNetDate;
}
function AddDay($date,$appoint_interval)
{
   /* echo "SELECT DATE_ADD('$date',INTERVAL $appoint_interval DAY)";
	echo "<br/>";*/
	$dateaddmin = mysql_query("SELECT DATE_ADD('$date',INTERVAL $appoint_interval DAY)");
	$AfterNetDate = mysql_result($dateaddmin, 0, 0); 
	return $AfterNetDate;
}
function removeQuotes($strToChange)
{
	//$strToChange=str_replace("'","&#39;",$strToChange);
	$strToChange=str_replace('"',"&quot;",$strToChange);
//	$strToChange=str_replace("\"","&quot;",$strToChange);
//	$strToChange=str_replace("\\","&#92;",$strToChange);

	return $strToChange;
}
//////////////////////////////////////////////////////////////////////


//*******  Call By Reference (A Variable $WeldNumber Is Created That Works As An Alias For $WeldNumber_UC) ***************

function getWeldDetails(&$WeldNumber)
{
     //------------------ Checking for Tie-in(T) or Free Tie-in(FT) -------------------
					$JointNumber = explode('M',$WeldNumber);
					   
					 if(empty($JointNumber[1]))
					 {
							$JointNumber = explode('FT',$WeldNumber);
							
								if(empty($JointNumber[1]))
								{
										$JointNumber = explode('TR',$WeldNumber);
											  
												 if(empty($JointNumber[1]))
												 {
														  $JointNumber = explode('GT',$WeldNumber);
														  if(empty($JointNumber[1]))
														  {
																			  $JointNumber = explode('T',$WeldNumber);
																				 
																				   if(empty($JointNumber[1]))
																				   {
																						 $JointNumber = explode('GJ',$WeldNumber);
																						 
																						 		if(empty($JointNumber[1]))
																				   				{
																						 			$JointNumber = explode('J',$WeldNumber);
																									 if(empty($JointNumber[1]))
																				   					 {
																						 
																						 
																						 // if no M,T,FT or TR is there in the Joint
																						 
																						 //Invalid Joint And Should Not Be Allowed To Enter And Header Should Be 
																						 //Transferred To The Point Where Welding Is Entered e.g. Welding.php
																				   					  }
																				   			else
																				   		 	 {
																						   $J1From = substr($JointNumber[0],1);
																						   $J2From = $JointNumber[1];
																						            // if J is There In The Joint
																				   		 	 }
																						 }
																				   		 else
																				   		 {
																						   $J1From = substr($JointNumber[0],1);
																						   $J2From = $JointNumber[1];
																						        // if GJ is There In The Joint
																				   		 }
																					}
																				   else
																				   {
																						   $J1From = substr($JointNumber[0],1);
																						   $J2From = $JointNumber[1];
																						  // if T is There In The Joint
																				   }
															}
															else
															{
																	  $J1From = substr($JointNumber[0],1);
																	  $J2From = $JointNumber[1];
																	  // if GT is There In The Joint
															}
												 }
												 else
												 {
														 $J1From = substr($JointNumber[0],1);
														 $J2From = $JointNumber[1];
														 // if TR is There In The Joint
												 }
												 
								}
								else
								{
										$J1From = substr($JointNumber[0],1);
										$J2From = $JointNumber[1];
										// if FT is There In The Joint
								}
					 } 
					 else
					 {
						$J1From = substr($JointNumber[0],1);
						$J2From = $JointNumber[1];
						// if M is There In The Joint    
					 }
					 
					 
		//*********** Regular Expression For J1From ********************
		
		 if(ereg("([0-9]{1,3})([A-Z]{1,2})",$J1From,$regsch))
		 {
			 //echo $regs[1]."-".$regs[2];
		 }
		 else
		 {
				 if(ereg("([0-9]{1,3})",$J1From,$regsch))
				 {
					 //echo $regs[1];
				 }
		 }
		//****************************************************************			 
					 
		//****  Regular Expression Pattern For J2From ******
		if(ereg("([0-9]{1,2})([A-Z]{1,2})([0-9]{1,2})([A-Z]{1,2})",$J2From,$regs))
		{
			  //echo $regs[1]."-".$regs[2]."-".$regs[3]."-".$regs[4];
		}
		else
		{
					if(ereg("([0-9]{1,2})([A-Z]{1,2})([0-9]{1,2})",$J2From,$regs))
					{
						 //echo $regs[1]."-".$regs[2]."-".$regs[3];
					}
					else
					{
						 if(ereg("([0-9]{1,2})([A-Z]{1,3})",$J2From,$regs))
						 {
							 //echo $regs[1]."-".$regs[2];
						 }
						 else
						 {
								 if(ereg("([0-9]{1,2})",$J2From,$regs))
								 {
									 //echo $regs[1];
								 }
						 }
					}
		}
		
		$Chainage = $regsch[1];
		$Chainage_Seq = $regsch[2];
		if($Chainage_Seq=='')
		{
		   $Chainage_Seq = 0;
		}
		
		$Seq = $regs[1];
		$SubSeq = $regs[2];
		if($SubSeq=='')
		{
		   $SubSeq = 0;
		}
		$SubSeq_Seq = $regs[3];
		
		return array($Chainage,$Chainage_Seq,$Seq,$SubSeq,$SubSeq_Seq);
		
}




// **************function to insert data in any table.***************
function insertData($table_name)
{
	$arr_types =  array("TRC_","TR_", "TN_", "TREF_", "PHR_", "PHN_", "IR_", "IN_", "MR_", "MN_", "TNEF_", "TRFN_", "TNFN_");
	if (!empty($GLOBALS["HTTP_POST_VARS"])) 
	{
		reset($GLOBALS["HTTP_POST_VARS"]);
		while (list($k,$v)=each($GLOBALS["HTTP_POST_VARS"])) 
		{
			for($p=0;$p<count($arr_types);$p++)
			{
				if(stristr($k,$arr_types[$p])!="")
				{
					$k = str_replace($arr_types[$p],"",$k);
				}
			}
			${strtolower($k)}=$v;
			//echo "<br> k =$k -- v = $v";
		}	
	}
	if (!empty($GLOBALS["HTTP_GET_VARS"])) 
	{
		reset($GLOBALS["HTTP_GET_VARS"]);
		while (list($k,$v)=each($GLOBALS["HTTP_GET_VARS"])) 
		{
			for($p=0;$p<count($arr_types);$p++)
			{
				if(stristr($k,$arr_types[$p])!="")
				{
					$k = str_replace($arr_types[$p],"",$k);
				}
			}
			${strtolower($k)}=$v;
			//echo "<br> k =$k -- v = $v";
		}	
	}
	$query1="";
	$query="";
	$result=mysql_query("show fields from $table_name");
	$query="insert into $table_name set ";
	while ($a_row = mysql_fetch_array($result, MYSQL_ASSOC)) 
	{
		$field="$a_row[Field]";
		if($field!='id')
		{
			if(isset($$field))
			{
				$query.=$field."=";
				$query.="'".removeQuotes ($$field)."' , ";
			}
			else
			{
				if(isset($GLOBALS["$field"]))
				{
					$query.=$field."=";
					$query.="'".removeQuotes ($GLOBALS["$field"])."' , ";
				}
			}
		}
	}
	//echo $query=substr($query,0,-2);
	$result=mysql_query($query);
	return $result;
}
//*************Function to edit data from any table.****************
function editData($table_name,$fldname,$fldval)
{
	$arr_types =  array("TR_", "TN_", "TREF_", "PHR_", "PHN_", "IR_", "IN_", "MR_", "MN_", "TNEF_", "TRC_", "TNC_", "TRFN_", "TNFN_");
	if (!empty($GLOBALS["HTTP_POST_VARS"])) 
	{
		reset($GLOBALS["HTTP_POST_VARS"]);
		while (list($k,$v)=each($GLOBALS["HTTP_POST_VARS"])) 
		{
			for($p=0;$p<count($arr_types);$p++)
			{
				if(stristr($k,$arr_types[$p])!="")
				{
					$k = str_replace($arr_types[$p],"",$k);
				}
			}
			${strtolower($k)}=$v;
		}	
	}
	if (!empty($GLOBALS["HTTP_GET_VARS"])) 
	{
		reset($GLOBALS["HTTP_GET_VARS"]);
		while (list($k,$v)=each($GLOBALS["HTTP_GET_VARS"])) 
		{
			for($p=0;$p<count($arr_types);$p++)
			{
				if(stristr($k,$arr_types[$p])!="")
				{
					$k = str_replace($arr_types[$p],"",$k);
				}
			}
			${strtolower($k)}=$v;
		}	
	}
	$result=mysql_query("show fields from $table_name");
	$query="update $table_name set ";
	while ($a_row = mysql_fetch_array($result, MYSQL_ASSOC)) 
	{
		$field="$a_row[Field]";
		if($field!=$fldname)
		{
			if(isset($$field))
			{
				$query.=$field."=";
				$query.="'".removeQuotes ($$field)."' , ";
			}
			else
			{
				if(isset($GLOBALS["$field"]))
				{
					$query.=$field."=";
					$query.="'".removeQuotes($GLOBALS["$field"])."' , ";
				}
			}
		}
	}
	$query = substr($query,0,-2);
	$query.="where $fldname='$fldval'"; 
	//echo "$query";
	$result=mysql_query($query);
	return $result;
}

//this function is for listing records pagewise
function pagelist($totalrow,$listrow,$links,$extra){
		$pages=$totalrow/$listrow;	//total no of page
		$str="";	// printing the page
		for($i=0;$i<$pages;$i++){
						$j=$i+1;	
						
						if($str=="")	
							$str= "<a class=paginglink href=\"$links?page=$i&$extra\">$j</a> ";
						else
							$str .= "| <a class=paginglink href=\"$links?page=$i&$extra\">$j</a>";
		}
		return $str;
}
function pagelist1($page,$totalrow,$listrow,$links,$extra){
		$pages=$totalrow/$listrow;	//total no of page
		$str="";	// printing the page
		for($i=0;$i<$pages;$i++){
						$j=$i+1;	
						if($i==$page)
						{
							if($str=="")	
							$str= "$j";
							else
							$str .= "| $j";
						}
						else
						{
							if($str=="")	
							$str= "<a class=paginglink href=\"$links?page=$i&$extra\">$j</a> ";
							else
							$str .= "| <a class=paginglink href=\"$links?page=$i&$extra\">$j</a>";
						}
						
		}
		return $str;
}



//////////////////////////////////////////////////////////////////////////
//******************************************************//
//function to fill fileld of form from database record


function getDatafillform($table,$fldName,$fldVal)
{
//echo "<br><br><br>"."select * from $table where $fldName='$fldVal'";

	$result=mysql_query("select * from $table where $fldName='$fldVal'");
	if(mysql_num_rows($result)>0)
	{
		$row=mysql_fetch_array($result);
		while (list($k,$v)=each($row)) 
		{
			if($k!=$fldName)
			{
				global ${$k};
				${$k}=$v;
			}
		}
		
		mysql_free_result($result);
		return $row;
	}
	else
	{
		return false;
	}
}

//*****************************************************//

// Function to get one record from anytable($table) having wny where clase($whereClause)
//*****************************************************//

function getAnyTableWhereData($table,$whereClause)
{
	//echo "<br> $table,$whereClause";
	$query="select * from $table where 1=1 $whereClause";
	$result=mysql_query($query);
	//return $result;
	//echo "<br>$query";
	if($row=mysql_fetch_array($result))
	{
//		echo "<br>enee $row[0]";
		mysql_free_result($result);
		return $row;
	}
	else
	{
//		echo "<br>no enee";
		return false;
	}
	
}


////////
### function to show date drop downs
function datelisting($date,$seldd="day",$selmm="month",$selyy="year",$startYear="",$endYear="")
	{
		list($year,$month,$day)= split ("-", $date);
 	  		 
        print '<select name="'.$seldd.'"><option value="">Date</option>';
     	$ct=0;
		for($ct=1;$ct<=31;$ct++)
		{
			echo "<option value='".($ct)."'";
			if($ct==$day)
			{
				 echo " selected";
			}
		   echo ">".$ct."</option>";
		}
		print "</select>";
        print" - ";
		print '<select name="'.$selmm.'"><option value="">Month</option>';
		$ct=0;
		for($ct=0;$ct<12;$ct++)
		{
			echo "<option value='".($ct+1)."'";

			if(($ct+1)==$month)
			{
				 echo " selected";
			}
			echo ">".date ("M", mktime (0,0,0,$ct+1,1,98)) ."</option>";
		}
		print'</select>';
		print" - ";
		print '<select name="'.$selyy.'"><option value="">Year</option>';
	  	$ct=0;
	
		if($startYear=="")
		{
			$s_yy=(date('Y')-10);
		}
		else
		{
			$s_yy = $startYear;
		}
		
		
		if($endYear=="")
		{
			$e_yy=(date('Y')+10);
		}
		else
		{
			$e_yy = $endYear;
		}

		for($ct=$s_yy;$ct<=$e_yy;$ct++)
		{
			echo "<option value='".($ct)."'";
			if($ct==$year)
			{
				 echo " selected";
			}
			echo ">".$ct."</option>";
		}
        print "</select>";
}
////////

### ============================================================ ###
function monthYearListing($monthName,$yearName,$month,$year,$startYear,$endYear)
{

		print '<select name="'.$monthName.'"><option value="">Month</option>';
		$ct=0;
		for($ct=0;$ct<12;$ct++)
		{
			echo "<option value='".($ct+1)."'";
			//if(($ct+1)==date('m'))
			if(($ct+1)==$month)
			{
				 echo " selected";
			}
			echo ">".date ("M", mktime (0,0,0,$ct+1,1,98)) ."</option>";
		}
		print'</select>';


		print" - ";
		print '<select name="'.$yearName.'"><option value="">Year</option>';
	  	$ct=0;

		if(isset($startYear) && $startYear!=""){}
		else{
			$startYear =1900;}

		if(isset($endYear) && $endYear!=""){}
		else{
			$endYear =(date('Y')+20);}

		for($ct=$startYear;$ct<=$endYear;$ct++)
		{
			echo "<option value='".($ct)."'";
			//if($ct==date('Y'))
			if(trim($ct)==trim($year))
			{
				 echo " selected";
			}
			echo ">".$ct."</option>";
		}
        print "</select>";

}

////////////////////////////////////////////////////////////////////////

//***************Mail Function***************************************//
function sendMail($to,$subject,$matter,$from)
{
    echo "hi";
	$headers  = "MIME-Version: 1.0\r\n"; 
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; 
	$headers .= "From:$from\r\n";
	
	if(mail($to,$subject,$matter,$headers))
	{
		return true;
	}
	else
	{
		return false;
	}

}
//**********************//

//***************Mail Function for text email ***************************************//
function sendtextMail($to,$subject,$matter,$from)
{
	$headers = "MIME-Version: 1.0\n";
//	$headers .= "Content-type: text/html; charset=iso-8859-1\n";
	$headers .= "X-Priority: 3\n";
	$headers .= "X-Mailer: PHP\n";
	$headers .= "X-Sender: $from\n";
	$headers .= "Return-Path: $from\n";
	$headers .= "From: $from\n";
	#$headers = "From:$from\r\nContent-Type:text/html; charset=iso-8859-1\r\n";
	if(mail("$to","$subject","$matter","$headers","-f $from"))
	{
		return true;
	}
	else
	{
		return false;
	}

}
//**********************//


//********************************************************//

//This function checks the size of an image and returns height and width if they exceed the maximum
Function CheckImageSize2($imageUrl)
{
	if($imDetail=getimagesize($imageUrl))
	{
		$iWidth = $imDetail[0];
		$iHeight = $imDetail[1];
		$toWidth=$iWidth;
		$toHeight=$iHeight;

//		echo "<br>max width = ".$GLOBALS["imMaxWidth"];
//		echo "<br>max height=".$GLOBALS["imMaxHeight"];

		if ($iWidth > $GLOBALS["imMaxWidth"] || $iHeight > $GLOBALS["imMaxHeight"])
		{
			
			

			if($toWidth>$GLOBALS["imMaxWidth"])
			{
				$toWidth=$GLOBALS["imMaxWidth"];
				$toHeight = ($toWidth/$iWidth)*$toHeight;

			}

			if($toHeight>$GLOBALS["imMaxHeight"])
			{
				$toHeight=$GLOBALS["imMaxHeight"];
				$toWidth = ($toHeight/$iHeight)*$toWidth;
			}
		}

		$idimension = " width = '$toWidth' height='$toHeight'";
//		echo $idimension;

	}
	else
	{
	//	echo "no getsize";
		$idimension ="";
	}
	return $idimension;
}

//********************************************************//

#################################################################
Function CheckImageSize($imageUrl)
{
//echo $imageUrl;
	$imMaxWidth=$GLOBALS["imMaxWidth"];
	$imMaxHeight=$GLOBALS["imMaxHeight"];
	$img_dim = array();
	if((file_exists($imageUrl)))
	{
//		echo $imageUrl."geeta";
		if($imDetail=getimagesize($imageUrl))
		{
			//print_r($imDetail);
			$iWidth = $imDetail[0];
			$iHeight = $imDetail[1];
			$toWidth=$iWidth;
			$toHeight=$iHeight;
	//		echo $iWidth." ".$iHeight." ".$imMaxWidth;
			if(($iWidth>=$iHeight) && ($iWidth>$imMaxWidth))
			{
				$newWidth=$imMaxWidth;
				$reduce_per=($imMaxWidth/$iWidth)*100;
				$newHeight=($iHeight*$reduce_per)/100;
	//			echo "here";
			}
			else if(($iWidth<$iHeight) && ($iHeight>$imMaxHeight))
			{
				$newHeight=$imMaxHeight;
				$reduce_per=($imMaxHeight/$iHeight)*100;
				$newWidth=($iWidth*$reduce_per)/100;
	//			echo $newHeight." dd ".$newWidth;
			}
			else
			{
				$newHeight=$iHeight;
				$newWidth=$iWidth;
			}
			$img_dim['width'] = round($newWidth);
			$img_dim['height'] = round($newHeight);

		}
		else
		{
			$img_dim['width'] = "";
			$img_dim['height'] = "";
		}
			
		$idimension = " width = '$img_dim[width]' height='$img_dim[height]'";
	//	print_r($img_dim);
	//	return $idimension;
	}
	
	//return $imageUrl;

	return $idimension;

}

##################################################################


function alternate_row($tdrow,$tdClass1,$tdClass2)
{

	
	if(($tdrow%2)==0)
	{
		$tdClass=$tdClass1;
	}
	else
	{
		$tdClass=$tdClass2;
	}
	
	return $tdClass;
}

///////////////////////////////////////////////////

/************************ function to display product images **********/
function displayProdImage($expToMatch,$prodID,$tableNm,$folderPath,$image_type="thumb_")
{
//function used to display the product images
				
				

				$imageQry="select * from $tableNm where prod_id='$prodID' and name_image like '$expToMatch%' ";
				$imageRec=mysql_query($imageQry);
				$imageRow=mysql_fetch_array($imageRec);

				if($imageRow)
				{
					$imageName=$imageRow["name_image"];
								
					if(strstr(strtolower($imageName),".gif")!="")
					{
						$thumbImage=$imageName;
					}
				    else
					{
						$thumbImage=$image_type.$imageName;	
					}
					$imagePath="../prod_images/".$thumbImage;
					$imageStr="<img src=\"$imagePath\"  ";
					if(strstr(strtolower($imageName),".gif")!="")
					{
						GLOBAL $imMaxWidth;
						GLOBAL $imMaxHeight;
						$imMaxWidth=$GLOBALS["add_img_desc_width"];
						$imMaxHeight=$GLOBALS["add_img_desc_height"];
						$imageStr.=CheckImageSize($imagePath);
					}
					
					$imageStr.=" border=0>";
					
					return 	$imageStr;
				}
				else
				{
					if($image_type=="thumb_")
					{
						$no_imageVar="no_image.gif";
					}
					else
					{
						$no_imageVar="no_image_large.gif";
					}
					return '<img src="images/'.$no_imageVar.'" alt="No Image Found" border=0>';
				}


}
/************************ function to display product images **********/




//////////////////////////////////////////////////

Function getNavigation($iCat, $last_link=0)
{
	$category_table = $GLOBALS["category_table"];
	$sNavBar="";
	$aclass=" class=crumb";
	If(trim($iCat)=="")
	{
		if($last_link==1)
		{
			echo "<a href='CategoriesManager.php' $aclass>Categories Manager</a> >> ";
		}
		else
		{
			echo "Categories Manager";
		}
	}
	Else
	{
		
		$navRs = mysql_query("SELECT parentid, categoryname, id FROM $category_table WHERE id='$iCat'");
		$navRow = mysql_fetch_array($navRs);
		If(mysql_num_rows($navRs)==0)
		{
		
			echo "<a href='CategoriesManager.php' $aclass>Categories Manager</a>";
		}
		Else
		{
		
			if($last_link==1)
			{
				$sLastCategory = " >> <a href='javascript:;' $aclass onClick=\"fnNavigate('$iCat','CategoriesManager.php');return false;\">" .$navRow["categoryname"]."</a> >> ";
			}
			else
			{
				$sLastCategory = " >> " .$navRow["categoryname"];
			}
			
			
			$iParent = $navRow["parentid"];
			While(!$iParent==0)
			{

				$loopRs = mysql_query("SELECT parentid, categoryname, id FROM $category_table WHERE id='$iParent'" );

				If(mysql_num_rows($loopRs)==0)
				{
					break;
				}
				$loopRow = mysql_fetch_array($loopRs);
				$iParent = $loopRow["parentid"];
				If($iParent==0)
				{
					$sNavBar =   " >> <a href='#' $aclass onClick=\"fnNavigate('$loopRow[id]','CategoriesManager.php');return false;\">$loopRow[categoryname]</a>".$sNavBar;
				}
				Else
				{
					If($sNavBar=="")
					{
						$sNavBar =  " >> <a href='#' $aclass onClick=\"fnNavigate('$loopRow[id] ','CategoriesManager.php');return false;\">$loopRow[categoryname]</a>";
					}
					Else
					{
						$sNavBar =  " >> <a href='#' $aclass onClick=\"fnNavigate('$loopRow[id] ','CategoriesManager.php');return false;\">$loopRow[categoryname]</a>".$sNavBar;

					}
				}
				
			}
		}

		echo "<a href='CategoriesManager.php' $aclass>Categories Manager</a>".$sNavBar.$sLastCategory;

	}
}
//////////////////////////////////////////////////
//*********************************************************//

Function GetCategoriesMain($CategoryID)
{
	$category_table = $GLOBALS["category_table"];
	If(trim($CategoryID)=="")
	{

		$query=("SELECT id, categoryname FROM $category_table WHERE isTop=1 ORDER BY categoryname");
	}
	Else
	{
		$query=("SELECT id, categoryname FROM $category_table WHERE parentid='$CategoryID' ORDER BY categoryname");
	}
$catRs=mysql_query($query);
	If(mysql_num_rows($catRs)==0)
	{
//		echo "No Categories Found!";
	}
	Else
	{
		$i=0;
		While($catRow = mysql_fetch_array($catRs)) 
		{

			$listCat[$i]="<a href='#' onClick=\"fnCatTraverse('".$catRow["id"] ."');return false;\">".$catRow["categoryname"]."</a>&nbsp;(".GetSubCategoriesSumMain($catRow["id"]).")";
			$i++;
		}
	}
	
	mysql_free_result($catRs);
	return $listCat;

}

Function GetSubCategoriesSumMain($iCatID)
{
	$category_table = $GLOBALS["category_table"];
	$product_table = $GLOBALS["product_table"];

	$rsCatSum = mysql_query("SELECT COUNT(*) AS TotRec FROM $category_table c,$product_table s WHERE s.category_id like c.id and (TopParent= '$iCatID' or parentid = '$iCatID' or s.category_id like '$iCatID')");
	$rowCatSum = mysql_fetch_row($rsCatSum);

	If(mysql_num_rows($rsCatSum)==0)
	{
		$getSubCategoriesSum = 0;
	}
	Else
	{
		If($rowCatSum[0]=="" || $rowCatSum[0]==0)
		{
			$getSubCategoriesSum =0;
		}
		Else
		{
			$getSubCategoriesSum =$rowCatSum[0];
		}
	}

return $getSubCategoriesSum;
}


//**********************//
//////////////////////////////////////////////////


Function CheckDuplicateUserNameID($sNameID, $sTblName, $sIDFld, $sExtraWhere)
{
	$rsLocal = mysql_query("SELECT $sIDFld FROM $sTblName WHERE $sIDFld = '$sNameID' $sExtraWhere");

	If(mysql_num_rows($rsLocal)==0)
	{
		$CheckDuplicateUserNameID = False;
	}
	Else
	{
		$CheckDuplicateUserNameID = True;
	}
	return $CheckDuplicateUserNameID;
	
}



//////////////////////////////////////////////////

function upload_my_file($upload_file,$destination)
{

	//move_uploaded_file
	if(move_uploaded_file($upload_file,$destination))
	{
		return true;
	}
	else
	{
		return false;
	}

}

##### End of File upload function #####


/**********************/
/////this is a simple function which only stores the one row of result set in a variable.
Function executeQuery($query)
{
	$result=mysql_query($query);
	if($row=mysql_fetch_array($result))
	{
		return $row;
	}
	else
	{
		return false;
	}
}
///////////////////////////




##### Imgage Functions ####

function create_thumb($path,$size,$save_path)
{
	if (file_exists($path))
	{

		if(strstr(strtolower($path),".gif")!="")
		{

		}
		else
		{
			
				$thumb=new my_thumbnail($path);	// generate image_file, set filename to resize
				$thumb->size_width(500);		// set width for thumbnail, or
				$thumb->size_height(500);		// set height for thumbnail, or

				$width=$thumb->img["lebar"];
				$height=$thumb->img["tinggi"];
				if($width>$size || $height>$size)
				{
					$size=$size;
				}
				else
				{
					$size=$width;
				}

				$thumb->size_auto($size);		// set the biggest width or height for thumbnail
				$thumb->jpeg_quality(100);		// [OPTIONAL] set quality for jpeg only (0 - 100) (worst - best), default = 75
			
		//		$thumb->show();					// show your thumbnail
				$thumb->save($save_path);		// save your thumbnail to file
//				echo "saved";
		}
			
	}
	else
	{
				return false;
	}
}
/*----------------------------------------------*/

class my_thumbnail
{
	
	var $img;

	function my_thumbnail($imgfile)
	{
		//
		//detect image format
		$this->img["format"]=ereg_replace(".*\.(.*)$","\\1",$imgfile);
		$this->img["format"]=strtoupper($this->img["format"]);
		if ($this->img["format"]=="JPG" || $this->img["format"]=="JPEG") {
			//JPEG
			
			$this->img["format"]="JPEG";
			$this->img["src"] = ImageCreateFromJPEG ($imgfile);

			
		} elseif ($this->img["format"]=="PNG") {
			//PNG
			$this->img["format"]="PNG";
			$this->img["src"] = ImageCreateFromPNG ($imgfile);
		} elseif ($this->img["format"]=="GIF") {
			//GIF
			$this->img["format"]="GIF";
			$this->img["src"] = ImageCreateFromGIF ($imgfile);
		} elseif ($this->img["format"]=="WBMP") {
			//WBMP
			$this->img["format"]="WBMP";
			$this->img["src"] = ImageCreateFromWBMP ($imgfile);
		} else {
			//DEFAULT
			echo "Not Supported File";
			exit();
		}

		@$this->img["lebar"] = imagesx($this->img["src"]);
		@$this->img["tinggi"] = imagesy($this->img["src"]);
		
		//default quality jpeg
		$this->img["quality"]=100;
	}

	function size_height($size=100)
	{
		//height
    	$this->img["tinggi_thumb"]=$size;

    	@$this->img["lebar_thumb"] = ($this->img["tinggi_thumb"]/$this->img["tinggi"])*$this->img["lebar"];
	}

	function size_width($size=100)
	{
		//width
		$this->img["lebar_thumb"]=$size;
    	@$this->img["tinggi_thumb"] = ($this->img["lebar_thumb"]/$this->img["lebar"])*$this->img["tinggi"];
	}

	function size_auto($size=100)
	{
		//size
		if ($this->img["lebar"]>=$this->img["tinggi"]) {
    		$this->img["lebar_thumb"]=$size;
    		@$this->img["tinggi_thumb"] = ($this->img["lebar_thumb"]/$this->img["lebar"])*$this->img["tinggi"];
		} else {
	    	$this->img["tinggi_thumb"]=$size;
    		@$this->img["lebar_thumb"] = ($this->img["tinggi_thumb"]/$this->img["tinggi"])*$this->img["lebar"];
 		}
	}

	function jpeg_quality($quality)
	{
		//jpeg quality
		$this->img["quality"]=$quality;
	}

	function show()
	{
		//show thumb
		@Header("Content-Type: image/".$this->img["format"]);

		/* change ImageCreateTrueColor to ImageCreate if your GD not supported ImageCreateTrueColor function*/
		$this->img["des"] = ImageCreateTrueColor($this->img["lebar_thumb"],$this->img["tinggi_thumb"]);
    		imagecopyresized ($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]);

		if ($this->img["format"]=="JPG" || $this->img["format"]=="JPEG") {
			//JPEG
			imageJPEG($this->img["des"],"",$this->img["quality"]);
		} elseif ($this->img["format"]=="PNG") {
			//PNG
			imagePNG($this->img["des"]);
		} elseif ($this->img["format"]=="GIF") {
			//GIF
			imageGIF($this->img["des"]);
//			echo "$path";

		} elseif ($this->img["format"]=="WBMP") {
			//WBMP
			imageWBMP($this->img["des"]);
		}
	}

	function save($save="")
	{
		//save thumb
		if (empty($save)) $save=strtolower("./thumb.".$this->img["format"]);
		/* change ImageCreateTrueColor to ImageCreate if your GD not supported ImageCreateTrueColor function*/
		$this->img["des"] = ImageCreateTrueColor($this->img["lebar_thumb"],$this->img["tinggi_thumb"]);
    		@imagecopyresized ($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]);

		if ($this->img["format"]=="JPG" || $this->img["format"]=="JPEG") {
			//JPEG
			imageJPEG($this->img["des"],"$save",$this->img["quality"]);
		} elseif ($this->img["format"]=="PNG") {
			//PNG
			imagePNG($this->img["des"],"$save");
		} elseif ($this->img["format"]=="GIF") {
			//GIF
			imageGIF($this->img["des"],"$save");
		} elseif ($this->img["format"]=="WBMP") {
			//WBMP
			imageWBMP($this->img["des"],"$save");
		}
	}
}

#####################################

### Function deletes the attributes of products ###

function deleteRecord($product_id,$table_name,$col_name)
{
	$attribute_table = $table_name;
	$att_value_table = $product_id;

	
	$del_query = "delete from $attribute_table where ".$col_name."='$product_id'";

		
	return mysql_query($del_query);
	
}

### End of Function deletes the attributes of products ###

### Function deletes the attributes of products ###

function deleteAttributes($product_id,$rootpath)
{
	$attribute_table = $GLOBALS["attribute_table"];
	$att_value_table = $GLOBALS["att_value_table"];

	$attach_temp_folder = $rootpath."product_images/";
	$attach_temp_folder1 = $rootpath."thumbs/";

	$r_att=mysql_query("select * from $attribute_table where product_id='$product_id'");

	$del_query = "delete from $attribute_table where product_id='$product_id'";

	while($row_att=mysql_fetch_array($r_att))
	{

		$r_att_val=mysql_query("select * from $att_value_table where attribute_id='".$row_att["id"]."'");	  
		$del_query1 = "delete from $att_value_table where attribute_id='".$row_att["id"]."'";
		while($row_att_val=mysql_fetch_array($r_att_val))
		{


			## Delete previous image ##

			if(trim($row_att_val["image"])!="")
			{
				$delFile=$attach_temp_folder."".trim($row_att_val["image"]);
				if(file_exists($delFile))
				{
					unlink($delFile);
					
					## remove thumbnail images ###
					$rfile1 = $attach_temp_folder1.trim($row_att_val["image"]);
					if(file_exists($rfile1))
					{
						unlink($rfile1);
					}
					## end of remove thumbnail images ###

				}
			}
			## End of Delete previous image ##

			
		}
		
		mysql_query($del_query1);
	}

	mysql_query($del_query);

}

### End of Function deletes the attributes of products ###



#################function to check wether user is valid for the page start#####################################

	function cofirmUserType($page_type)
	{
		
		$sess_admin_type=$_SESSION['sess_admin_type'];
		
		if(isset($sess_admin_type) && $sess_admin_type!="")
		{

			switch($sess_admin_type)
			{
				case "SA": 	break;

				case "AD":
							if($page_type=="SA")
							{
								header("location: index.php?err=type");
								break;
								die();
							}
							else
							{
								break;
							}
				
				case "SR":						
							if($page_type=="AD" || $page_type=="SA")
							{
								header("location: index.php?err=type");
								break;
								die();
							}
							else
							{
								break;
							}
			}
		
		}
		else
		{
				header("location: index.php?err=register");
				die();
		}
		
	}



#################function to check wether user is valid for the page ends#####################################

#########################Function to format date ##################
function show_formatted_date($p_date)
{
//	echo "<br> pdate = $p_date";
//	echo date('d F, Y',strtotime($p_date));
	 return date('jS F, Y',strtotime($p_date));
}

function show_formatted_datetime($p_date)
{
//	echo "<br> pdate = $p_date";
//	echo date('d F, Y',strtotime($p_date));
	 return date('jS F Y h:i A',strtotime($p_date));
	 
}
#########################Function to format date ##################

#########################Function to get admin name ##################
function getAdminName($adminid)
{	
	$adminarray=array();
	$admin_row=getAnyTableWhereData($GLOBALS['admin_login_table'], " and id=$adminid");
	$adminarray[0]=$admin_row['first_name'].' '.$admin_row['last_name'];
	if($admin_row['admin_type']=='SA' || $admin_row['admin_type']=='AD')
	{
		$adminarray[1]="Admin";
	}
	else
	{
		 $adminarray[1]="Sales Representative";
	}
	
	return $adminarray;
}
#########################Function to get admin name ##################



function display_paging($total_recs,$paging,$page)
{
####################admin paging starts ##################
$paging_table="";
if($total_recs>0){
			
			$no_of_page=ceil($total_recs/$paging);
//			print "<p align=center class=content>Page ".($page+1)." of $no_of_page ";
			$paging_table="<table width=400 border=0 align=right cellpadding=2 cellspacing=0>
                <tr> 
                <td class=\"pagingtxt\" align=\"right\"> <br>Paging: ";
			for($i=0;$i<$no_of_page;$i++){
				$j=$i+1;
				if($i!=$page) $paging_table.=" <a href=\"javascript:page_list('$i');\" class=\"paginglink\">$j</a> ";
				else $paging_table.= $j;
				$paging_table.= " | ";
			}

			$paging_table= substr($paging_table,0,-2);
				//$paging_table.= "[<font class=content>".$j."</font>]";
			$paging_table.= " </p> </td> </tr>";
			  $paging_table.="</table>";
}
	if(isset($no_of_page) && ($no_of_page<=1))
	{
		$paging_table="";
	}
				return $paging_table;
#################### paging Ends ##################

}


function userdisplay_paging($total_recs,$paging,$page)
{
####################admin paging starts ##################
$paging_table="";
if($total_recs>0){
			$paging = 30;
			$no_of_page=ceil($total_recs/$paging);
//			print "<p align=center class=content>Page ".($page+1)." of $no_of_page ";
			$paging_table="<table width=400 border=0 align=right cellpadding=2 cellspacing=0>
                <tr> 
                <td class=\"pagingtxt\" align=\"right\"> <br>";
			for($i=0;$i<$no_of_page;$i++){
				$j=$i+1;
				if($i!=$page) $paging_table.=" <a href=\"javascript:page_list('$i');\" class=\"userpaginglink\">$j</a> ";
				else $paging_table.= $j;
				$paging_table.= " | ";
			}

			$paging_table= substr($paging_table,0,-2);
				//$paging_table.= "[<font class=content>".$j."</font>]";
			$paging_table.= " </p> </td> </tr>";
			  $paging_table.="</table>";
}
	if(isset($no_of_page) && ($no_of_page<=1))
	{
		$paging_table="";
	}
				return $paging_table;
#################### paging Ends ##################

}

#######################  function to show state options ################  
function show_state($Default_state)
{
		$STATE_Query="select * from ".$GLOBALS['states_table']." where status=$GLOBALS[GL_active] order by state_name";
		//echo $STATE_Query;
		$STATE_Result=mysql_query($STATE_Query);
		$STATE_String="";
		while($STATE_Row=mysql_fetch_array($STATE_Result))
		{
			$STATE_String.="<option value='".$STATE_Row['id']."'";
			
			if((isset($Default_state)) && ($Default_state!="") && ($Default_state==$STATE_Row['id']))
			{
				$STATE_String.=" Selected ";
			}
			$STATE_String.=">".$STATE_Row['state_name']."</option>";
		}
		return $STATE_String;
}




#######################  function to show state options ################  

#######################  function to show county options ################  


function show_category_type($Default_type)
{
	


		if(strstr($Default_type,","))
		{
			$arr=explode(",",$Default_type);
		}
		else
		{
			$arr=$Default_type;
		}
		

	

	
	$TYPE_Query="select * from ".$GLOBALS['category_type_table']." where status=$GLOBALS[GL_active] order by category_type";
		//echo $type_Query;
		$TYPE_Result=mysql_query($TYPE_Query);
		$TYPE_String="";
		while($TYPE_Row=mysql_fetch_array($TYPE_Result))
		{
			$TYPE_String.="<option value='".$TYPE_Row['id']."'";
			
			if((isset($Default_type)) && ($Default_type!="") )
			{
				for($i=0;$i<sizeof($arr);$i++)
				{
					if($arr[$i]==$TYPE_Row['id'])
					{
						$TYPE_String.=" Selected ";
					}
				}
				
			}
			$TYPE_String.=">".$TYPE_Row['category_type']."</option>";
		}
		
		
		return $TYPE_String;
}

#######################  function to show category options ################  
function show_category($Default_region)
{
		$CATEGORY_Query="select * from ".$GLOBALS['category_table']." where status=$GLOBALS[GL_active] order by category_name";
		echo $CATEGORY_Query;
		$CATEGORY_Result=mysql_query($CATEGORY_Query);
		$CATEGORY_String="";
		while($CATEGORY_Row=mysql_fetch_array($CATEGORY_Result))
		{
			$CATEGORY_String.="<option value='".$CATEGORY_Row['id']."'";
			
			if((isset($Default_region)) && ($Default_region!="") && ($Default_region==$CATEGORY_Row['id']))
			{
				$CATEGORY_String.=" Selected ";
			}
			$CATEGORY_String.=">".$CATEGORY_Row['category_name']."</option>";
		}
		return $CATEGORY_String;
}
###########################################################################
function show_region($Default_region)
{
		$REGION_Query="select * from ".$GLOBALS['region_table']." where status=$GLOBALS[GL_active] order by region";
		echo $REGION_Query;
		$REGION_Result=mysql_query($REGION_Query);
		$REGION_String="";
		while($REGION_Row=mysql_fetch_array($REGION_Result))
		{
			$REGION_String.="<option value='".$REGION_Row['id']."'";
			
			if((isset($Default_region)) && ($Default_region!="") && ($Default_region==$REGION_Row['id']))
			{
				$REGION_String.=" Selected ";
			}
			$REGION_String.=">".$REGION_Row['region']."</option>";
		}
		return $REGION_String;
}
function show_region1($state_id)
{
		$REGION_Query="select * from ".$GLOBALS['region_table']." where status=$GLOBALS[GL_active] and state_id=$state_id order by region";
		echo $REGION_Query;
		$REGION_Result=mysql_query($REGION_Query);
		$REGION_String="";
		while($REGION_Row=mysql_fetch_array($REGION_Result))
		{
			$REGION_String.="<option value='".$REGION_Row['id']."'";
			
			
			$REGION_String.=">".$REGION_Row['region']."</option>";
		}
		return $REGION_String;
}

// FUNCTION TO create hidden fields for going back
function hiddenFields(){
	$h="";
	if (!empty($GLOBALS["HTTP_POST_VARS"])) {
		reset($GLOBALS["HTTP_POST_VARS"]);
		while (list($k,$v)=each($GLOBALS["HTTP_POST_VARS"])) 
		{
			$h .= "<input type=\"hidden\" name=\"$k\" value=\"$v\">\n";			
		}
		echo $h;
	}
}

//function for trimming the string if it more than specific number of characters
//$strng  String
//$count  number of characters 
//returns the trimmed string
function trimString($strng,$count_chars)
{
       if(strlen($strng)>$count_chars)
	   {
			$str_new=substr($strng,0,$count_chars);
            $str_new.=".....";
			return $str_new;
	   }
	   else
	   {
		   return $strng;
	   }	
}
//////  This Function Replaces All Characters In A String ($string) With A Specified Character($char) Passed
//////  As An Argument To this Function

/////   Example : if $string=="abcde" , then the resulting string would be:- $result="xxxxx" (if $char=='x')
function replaceString($string,$char)
{
     $len = strlen($string);
	 $result="";
	 for($i=0;$i<$len;$i++)
	 {
	     $result.=$char;
	 }
	 return($result);
}
function traverse($array_business_category,$index,$i=1,$prevn,$final)
{
    $i=1;
    for($j=$index;$j>0;$j--)
	{
	    $string = $array_business_category[$j];
	
		$substr = "- ";
		$resultStr = replaceSubString($string,$substr);
		$n = substr_count($string,'- '); 
		
		if($i==1)
		{
			
			$final = $resultStr;
			$prevn = $n;
			$i++;
			
		}
		elseif($i>1)
		{
				if($n>0)
				{
					  
						  if($n==($prevn-1))
						  {
							 $final.= ":".$resultStr;
						  }
						  
						  $prevn=$n;
						  $i++;
				}
				elseif($n==0)
				{
					  
					   $final.= ":".$resultStr;
					   
					   break;
					   
				}   
				
		}
		
   }
   $finalarr = explode(":",$final);
   
   $reversearr = array_reverse($finalarr,false);
   
   $len = count($reversearr);
   
   for($k=0;$k<$len;$k++)
   {
       if($k==($len-1))
	   {
	      $finalResult.= $reversearr[$k];
	   }
	   else
	   {
	      $finalResult.= $reversearr[$k].":";
	   }
       
   }
   
   return($finalResult);
}
function traverseRecursive($array_business_category,$index,$i=1,$prevn,$final)
{
    $string = $array_business_category[$index];
	
	$substr = "- ";
	$resultStr = replaceSubString($string,$substr);
	$n = substr_count($string,'- '); 
	
	
	if($i==1)
	{
	    $prevn = $n;
		$final = $resultStr;
		$i++;
		traverse($array_business_category,$index-1,$i,$prevn,$final);  
	}
	elseif($i>1)
	{
	    if($n>0)
		{
		    
			  if($prevn==$n)
			  {
			       
			       $prevn=$n;
				   $i++;
				   traverse($array_business_category,$index-1,$i,$prevn,$final);
			  }
			  elseif($n==($prevn-1))
			  {
			     
				 $final.= ":".$resultStr;
				 $prevn=$n;
				 $i++;
				 traverse($array_business_category,$index-1,$i,$prevn,$final);
				 
			  }
		}
	    elseif($n==0)
		{
		      
			   $final.= ":".$resultStr;
			   
		}   
	    
	}
	
}

//////  This function Replaces A Particular SubString From A Whole String 
//////  And Gives The Resulting String With Specified SubString Replaced
function replaceSubString($string,$substr)
{
    $resultStr = str_replace($substr,"",$string);
	return($resultStr);
}

function timeadd($diff_seconds,$id,$timefrom,$business_hours_table)
{
  
   $truncate_SQL="truncate table `business_hours1`";
   mysql_query($truncate_SQL);
   $insert_time_to_seconds_SQL="INSERT INTO `business_hours1` ( `id`,`sec` ) 
   VALUES ('$id','$diff_seconds')";
   mysql_query($insert_time_to_seconds_SQL);
   
   $get_sec_to_time_SQL="select sec_to_time(sec) as timediff from `business_hours1` where 1=1";
   $get_sec_to_time_Query=mysql_query($get_sec_to_time_SQL);
   $get_sec_to_time_Data = mysql_fetch_array($get_sec_to_time_Query);
   $timediff=$get_sec_to_time_Data['timediff'];
   
   $truncate_SQL="truncate table `business_hours2`";
   mysql_query($truncate_SQL);
	
   $insert_time_add_seconds_SQL="INSERT INTO `business_hours2` ( `id`,`timefrom`,`timediff` ) 
VALUES ('$id','$timefrom','$timediff')";
   mysql_query($insert_time_add_seconds_SQL);
   
   $Get_Time_To_SQL="SELECT timefrom, timediff, SEC_TO_TIME( MOD( TIME_TO_SEC( timefrom ) + TIME_TO_SEC( timediff ) , 86400 ) ) AS 't1 + t2'
FROM business_hours2";
   $Get_Time_To_Query=mysql_query($Get_Time_To_SQL);
   $Get_Time_To_Data=mysql_fetch_array($Get_Time_To_Query);
   
   $result=$Get_Time_To_Data['t1 + t2'];
   return $result;
   
}
function timeadd30Min($interval,$id,$timetonew1,$business_hours_table)
{
	   $truncate_SQL="truncate table `business_hours3`";
	   mysql_query($truncate_SQL);
		
	   $insert_time_add_seconds_SQL="INSERT INTO `business_hours3` ( `id`,`timeto`,`interval` ) 
	   VALUES ('$id','$timetonew1','$interval')";
	   mysql_query($insert_time_add_seconds_SQL);
	   
	   $Get_Time_To_SQL="SELECT `timeto`, `interval`,SEC_TO_TIME( MOD( TIME_TO_SEC(`timeto`) +  TIME_TO_SEC( `interval`) , 86400 ) ) AS 't1 + t2' FROM `business_hours3`";
	   $Get_Time_To_Query=mysql_query($Get_Time_To_SQL);
	   $Get_Time_To_Data=mysql_fetch_array($Get_Time_To_Query);
	   
	   $result=$Get_Time_To_Data['t1 + t2'];
	   return $result;
}
function datediff($interval, $date1, $date2) {
   // Function roughly equivalent to the ASP "DateDiff" function
  
   /* Get the seconds first */
   $seconds = strtotime($date2) - strtotime($date1);

   $date1=date("Y-m-d", strtotime($date1));
   $date2=date("Y-m-d",strtotime($date2));
  
   switch($interval) {
       case "y":
           list($year1, $month1, $day1) = split('-', $date1);
           list($year2, $month2, $day2) = split('-', $date2);
           $time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1));
           $time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2));
           $diff = $year2 - $year1;
           if($month1 > $month2) {
               $diff -= 1;
           } elseif($month1 == $month2) {
               if($day1 > $day2) {
                   $diff -= 1;
               } elseif($day1 == $day2) {
                   if($time1 > $time2) {
                       $diff -= 1;
                   }
               }
           }
           break;
       case "m":
           /* parses the year, month and days. split() was replaced with explode(), PHP Manual says it's faster */
           list($year1, $month1, $day1) = explode('-', $date1);
           list($year2, $month2, $day2) = explode('-',$date2);

           $time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1));
           $time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2));
           
           $diff = ($year2 * 12 + $month2) - ($year1 * 12 + $month1);

           if($day1 > $day2) {
               $diff -= 1;
           } elseif($day1 == $day2) {
               if($time1 > $time2) {
                   $diff -= 1;
               }
           }
           break;
       case "w":
           // Only simple seconds calculation needed from here on
           $diff = floor($seconds / 604800);
           break;
       case "d":
           $diff = floor($seconds / 86400);
           break;
       case "h":
           $diff = floor($seconds / 3600);
           break;      
       case "i":
           $diff = floor($seconds / 60);
           break;      
       case "s":
           $diff = $seconds;
           break;      
   }
   //return the +ve integer only
   if ($diff<0){
     $diff=0-$diff;
   }
   return $diff;
}

function datediff1($interval, $date1, $date2) {
   // Function roughly equivalent to the ASP "DateDiff" function
  
   /* Get the seconds first */
   $seconds = strtotime($date2) - strtotime($date1);

   $date1=date("Y-m-d", strtotime($date1));
   $date2=date("Y-m-d",strtotime($date2));
  
   switch($interval) {
       case "y":
           list($year1, $month1, $day1) = split('-', $date1);
           list($year2, $month2, $day2) = split('-', $date2);
           $time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1));
           $time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2));
           $diff = $year2 - $year1;
           if($month1 > $month2) {
               $diff -= 1;
           } elseif($month1 == $month2) {
               if($day1 > $day2) {
                   $diff -= 1;
               } elseif($day1 == $day2) {
                   if($time1 > $time2) {
                       $diff -= 1;
                   }
               }
           }
           break;
       case "m":
           /* parses the year, month and days. split() was replaced with explode(), PHP Manual says it's faster */
           list($year1, $month1, $day1) = explode('-', $date1);
           list($year2, $month2, $day2) = explode('-',$date2);

           $time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1));
           $time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2));
           
           $diff = ($year2 * 12 + $month2) - ($year1 * 12 + $month1);

           if($day1 > $day2) {
               $diff -= 1;
           } elseif($day1 == $day2) {
               if($time1 > $time2) {
                   $diff -= 1;
               }
           }
           break;
       case "w":
           // Only simple seconds calculation needed from here on
           $diff = floor($seconds / 604800);
           break;
       case "d":
           $diff = floor($seconds / 86400);
           break;
       case "h":
           $diff = floor($seconds / 3600);
           break;      
       case "i":
           $diff = floor($seconds / 60);
           break;      
       case "s":
           $diff = $seconds;
           break;      
   }
   //return the +ve integer only
   
   return $diff;
}

function get_column_names($tbl_name)
{
	$query ="SHOW COLUMNS FROM $tbl_name";
	if(!($result_id = mysql_query($query)))
		return false;
	$names = array();
	while(list($name) = mysql_fetch_row($result_id))
		$names[] = $name;
	mysql_free_result($result_id);
	return($names);
}

function checkStaffLimit($business_id, $limit) {
	$query = "select count(*) as count from staff where business_id='$business_id'";
	$res = mysql_query($query) or die(mysql_error());
	$row = mysql_fetch_object($res);
	if($row->count < $limit)
		return true;
	else 
		return false;
}

function setSpreadSection($table_name, $Spread, $Section)
{   
    //  Spread & Section Column Names should be there in the table 
    $User_Spread=$_SESSION['User_Spread'];
	$User_Section=$_SESSION['User_Section'];
	if(($_SESSION['ALevel'] == 'admin') || ($User_Spread=='' && $User_Section==''))
	{
			$oq="Select * from $table_name";
	}
	elseif($User_Section =='')
	{
			$oq="Select * from $table_name where $Spread = '$User_Spread'";
	}
	elseif($User_Spread!='' && $User_Section!='')
	{
	      
			$oq="Select * from $table_name where $Spread = '$User_Spread'  AND $Section = '$User_Section'";
	}
	return $oq;
}

function begin() 
{
@mysql_query("BEGIN");
}
function commit()
{
@mysql_query("COMMIT");
}
function rollback()
{
@mysql_query("ROLLBACK");
}


?>
